package com.snowj.apaas.web;

import com.snowj.apaas.security.SecurityUtils;
import com.snowj.apaas.domain.auto.Users;
import com.snowj.apaas.service.AuthService;
import com.snowj.apaas.service.UsersService;
import com.snowj.apaas.service.utils.ResponseUtil;
import com.snowj.apaas.web.vm.LoginVM;
import com.snowj.apaas.web.vm.UsersVm;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

@RestController
@RequestMapping("/api")
public class AuthorizationController {

    private final AuthService authService;

    private final UsersService usersService;

    public AuthorizationController(AuthService authService, UsersService usersService) {
        this.authService = authService;
        this.usersService = usersService;
    }

   @PostMapping("/change-password")
   public ResponseEntity<Boolean> changePassword(@RequestBody LoginVM loginVM) {
       boolean result = authService.changePassword(loginVM);
       return ResponseEntity.ok().body(result);
   }

    @PostMapping("/change-own-password")
    public ResponseEntity<Boolean> changeOwnPassword(@RequestBody LoginVM loginVM) {
        boolean result = authService.changeOwnPassword(loginVM);
        return ResponseEntity.ok().body(result);
    }
    @GetMapping("/login")
    public Object modelAndView(HttpServletRequest request, HttpServletResponse response) {
        String xRequestedWith = request.getHeader("X-Requested-With");
        if ("XMLHttpRequest".equals(xRequestedWith)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        // 未登录，跳转登录页面
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login");

        return modelAndView;
    }

    @GetMapping("/redirect")
    public void redirect(HttpServletResponse response, @RequestParam String redirect_url) {
        try {
            response.sendRedirect(redirect_url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/currentUser")
    public ResponseEntity<UsersVm> whoami() {
        String login = SecurityUtils.getCurrentUserLogin();
        Optional<UsersVm> users = usersService.getUserByUsername(login);
        return ResponseUtil.wrapOrNotFound(users);
    }

    @GetMapping("/auth/user")
    public ResponseEntity<Users> currentUserInfo() {
        Optional<Users> userInfo = authService.currentUserInfo();
        return userInfo.map(users -> ResponseEntity.ok().body(users))
                .orElseGet(() -> ResponseEntity.notFound().build());
    }
}
